package cn.edu.xaut.rssirecoder;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;

public class MainActivity extends AppCompatActivity {

    private WifiManager wifiManager;
    private WifiReceiver wifiReceiver;
    private ArrayList<HashMap<String, String>> listContent;
    private SimpleAdapter adapter;

    private TextView tvNum;
    private TextView tvCount;
    private TextView tvLast;
    private TextView tvDegree;

    private HashMap<String, String> mapMac;
    private File logFile;
    private Thread threadPosition;
    private boolean refreshDegree=true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        listContent = new ArrayList<>();
        adapter = new SimpleAdapter(this, listContent, R.layout.rssi, new String[]{"tvNo", "tvBSSID", "tvRSSI"}, new int[]{R.id.tvNo, R.id.tvBSSID, R.id.tvRSSI});
        initMapMac();

        tvCount = (TextView) findViewById(R.id.tvCount);
        tvNum = (TextView) findViewById(R.id.tvNum);
        tvLast=(TextView)findViewById(R.id.tvLast);
        tvDegree=(TextView)findViewById(R.id.tvDegree);
        Button btnAdd = (Button) findViewById(R.id.btnAdd);
        Button btnSubtract = (Button) findViewById(R.id.btnSubtract);
        Button btnGet = (Button) findViewById(R.id.btnGet);
        Button btnRecord = (Button) findViewById(R.id.btnRecord);
        ListView listView = (ListView) findViewById(R.id.listRSSI);

        if ((btnAdd != null) && (btnSubtract != null) && (btnGet != null) && (btnRecord != null) && (listView != null)) {
            btnRecord.setOnClickListener(onClickListenerBtnRecord);
            btnGet.setOnClickListener(onClickListenerBtnGet);
            btnAdd.setOnClickListener(onClickListenerBtnAdd);
            btnSubtract.setOnClickListener(onClickListenerBtnSubtract);
            listView.setAdapter(adapter);
        }

        Message message = new Message();
        initHandler.sendMessage(message);
    }

    private void initFile() {
        String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
        baseDir += File.separator;
        baseDir += "RSSI";
        baseDir += File.separator;
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-HH",Locale.CHINA);
        String dateString = formatter.format(currentTime);
        boolean result;
        try {
            File dir = new File(baseDir);
            if (!dir.exists()) {
                result = dir.mkdirs();
                Log.d("File Create", result + "");
            }
        } catch (Exception e) {
            Log.d("File Error", e + "");
        }
        try {
            logFile = new File(baseDir + "RSSI-" + dateString + ".txt");
            if (!logFile.exists()) {
                result = logFile.createNewFile();
                Log.d("File Create", result + "");
            }
        } catch (Exception e) {
            Log.d("File Error", e + "");
        }
    }

    private void initMapMac() {
        mapMac = new HashMap<>();
        mapMac.put("6c:3b:6b:44:32:d3", "1");
        mapMac.put("6c:3b:6b:48:bd:ad", "2");
        mapMac.put("6c:3b:6b:48:c0:5f", "3");
        mapMac.put("6c:3b:6b:48:c3:3e", "4");
    }

    View.OnClickListener onClickListenerBtnAdd = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            int tmp = Integer.parseInt(tvNum.getText().toString());
            tmp++;
            tvNum.setText(tmp + "");
        }
    };

    View.OnClickListener onClickListenerBtnSubtract = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            int tmp = Integer.parseInt(tvNum.getText().toString());
            if (tmp > 0) {
                tmp--;
                tvNum.setText(tmp + "");
            } else {
                tvNum.setText("0");
            }
        }
    };

    View.OnClickListener onClickListenerBtnGet = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Message message = new Message();
            initHandler.sendMessage(message);
        }
    };

    View.OnClickListener onClickListenerBtnRecord = new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            if(logFile==null){
                initFile();
            }

            Date currentTime = new Date();
            SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss", Locale.CHINA);
            String dateString = formatter.format(currentTime);
            String record = tvNum.getText().toString();
            record += "_";
            if (listContent.size() > 0) {
                for (int i = 0; i < listContent.size(); i++) {
                    HashMap<String, String> tmp = listContent.get(i);
                    record = record + tmp.get("tvNo") + "_" + tmp.get("tvRSSI") + "_";
                }
            }
            record += tvDegree.getText();
            record += dateString;
            try {
                BufferedWriter out = new BufferedWriter(new FileWriter(logFile, true));
                out.write(record);
                out.newLine();
                out.flush();
                out.close();
                Toast.makeText(MainActivity.this, "记录成功：" + record, Toast.LENGTH_SHORT).show();
            } catch (IOException e) {
                e.printStackTrace();
            }

            tvLast.setText(tvNum.getText().toString());
        }
    };

    private Handler initHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 0x1);
                Message message = new Message();
                initHandler.sendMessage(message);
            } else {
                Init();
            }
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0x2);
                Message message = new Message();
                initHandler.sendMessage(message);
            }

        }
    };

    private void Init() {
        startThreadPosition();
        wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
        //CloseWifi();
        OpenWifi();
        Log.d("STATE:", wifiManager.getWifiState() + "");
        Toast.makeText(this, "开始扫描Wifi", Toast.LENGTH_SHORT).show();
        wifiReceiver = new WifiReceiver();
        registerReceiver(wifiReceiver, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
        wifiManager.startScan();
    }

    private void OpenWifi() {
        if (!wifiManager.isWifiEnabled()) {
            wifiManager.setWifiEnabled(true);
        }
    }

    private void CloseWifi() {
        if (wifiManager.isWifiEnabled()) {
            wifiManager.setWifiEnabled(false);
        }
    }

    protected void onPause() {
        super.onPause();
        refreshDegree=false;
        unregisterReceiver(wifiReceiver);
    }

    private final class WifiReceiver extends BroadcastReceiver {
        public void onReceive(Context context, Intent intent) {
            Toast.makeText(MainActivity.this, "Wifi扫描结束", Toast.LENGTH_SHORT).show();
            List<ScanResult> scanResults = wifiManager.getScanResults();
            int count = 0;
            listContent.clear();
            HashMap<String, String> usefulInfo;
            for (ScanResult tmp : scanResults) {
                if (tmp.SSID.equals("iXAUT")) {
                    String mac = tmp.BSSID;
                    String no = mapMac.get(mac);
                    if (no == null) {
                        no = "0";
                    }
                    usefulInfo = new HashMap<>();
                    usefulInfo.put("tvNo", no);
                    usefulInfo.put("tvBSSID", mac);
                    usefulInfo.put("tvRSSI", tmp.level + "");
                    listContent.add(usefulInfo);
                    count++;
                }
            }
            Collections.sort(listContent, new Comparator<Map<String, String>>() {
                @Override
                public int compare(Map<String, String> o1, Map<String, String> o2) {
                    int val1 = Integer.parseInt(o1.get("tvNo"));
                    int val2 = Integer.parseInt(o2.get("tvNo"));
                    return (val1 < val2 ? -1 : (val1 == val2 ? 0 : 1));
                }
            });
            tvCount.setText(count + "");
            adapter.notifyDataSetChanged();
            unregisterReceiver(wifiReceiver);
        }
    }

    private void startThreadPosition() {
        Intent directionService = new Intent(this, DirectionService.class);
        startService(directionService);
        if (threadPosition == null) {
            threadPosition = new Thread() {// 子线程用于监听当前步数的变化
                @Override
                public void run() {
                    super.run();
                    while (refreshDegree) {
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        Message msg = new Message();
                        handlerPosition.sendMessage(msg);// 通知主线程
                    }
                }
            };
            threadPosition.start();
        }
    }

    private Handler handlerPosition = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            String degree=String.valueOf(DirectionFunc.CURRENT_DEGREE);
            tvDegree.setText(degree.substring(0,(degree.indexOf(".")+2)<degree.length()?(degree.indexOf(".")+2):degree.length()));
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
        refreshDegree=true;
    }
}
